<template>
	<div class="pdf_viewer_container">
		<div class="tool_bar" v-show="totalPageNum != 0">
			<div class="page_num">{{ currentPageNum }} / {{ totalPageNum }}页</div>
			<span class="txt">放大</span>
			<div class="box">
				<div class="mask" v-show="zoom == maxZoom"></div>
				<van-icon name="plus" size="18" @click="zoomChange('plus')" />
			</div>
			<span class="txt">缩小</span>
			<div class="box">
				<div class="mask" v-show="zoom == minZoom"></div>
				<van-icon name="minus" size="18" @click="zoomChange('minus')" />
			</div>
		</div>
		<div class="pdf-viewer" @scroll="onScroll">
			<template v-for="item in totalPageNum" :key="item">
				<canvas
					class="pdf_item"
					:id="`pdf-canvas-${item}`"
					:style="{ zoom: zoom / 10 }"
				/>
			</template>
		</div>
	</div>
</template>

<script>
import {
	reactive,
	toRefs,
	getCurrentInstance,
	nextTick,
	watchEffect
} from 'vue'
import * as pdfjs from 'pdfjs-dist/legacy/build/pdf.js'
// import {GlobalWorkerOptions, getDocument} from 'pdfjs-dist'
// import pdfjsWorker from 'pdfjs-dist/build/pdf.worker.entry'
pdfjs.GlobalWorkerOptions.workerSrc = require('pdfjs-dist/build/pdf.worker.entry')

export default {
	props: {
		url: {
			type: String,
			default: '' // pdf文件路径
		}
	},
	setup(props, { emit }) {
		/* vue3 proxy 相当于 vue2 this */
		const { proxy } = getCurrentInstance()
		const state = reactive({
			pdfCtx: null,
			currentPageNum: 0, // 当前页
			totalPageNum: 0,
			zoom: 10, // 目前暂时采用css方式缩放页面
			minZoom: 10, // 缩放最小值 一倍
			maxZoom: 50 // 缩放最大值 五倍
		})
		let pdfCtx = null
		const methods = {
			resolvePdf (url) {
				const loadingTask = pdfjs.getDocument(url)
				loadingTask.promise.then((pdf) => {/*  */
					console.log('pdf', pdf)
					pdfCtx = pdf
					state.totalPageNum = pdf.numPages
					state.currentPageNum = 1
					// 动态计算scale
					pdf.getPage(1).then((page) => {
						console.log(page, "0000000000000")
						let boxWidth = document.body.clientWidth - 20
						const [x1, , x2] = page._pageInfo.view
						const pageWidth = x2 - x1
						state.scale = (boxWidth * (state.maxZoom / 10)) / pageWidth
					})
					nextTick(() => {
						methods.renderPdf()
					})
				})
			},
			renderPdf (num = 1) {
				console.log(pdfCtx, 'pdfCtx')
				pdfCtx.getPage(num).then((page) => {
					console.log('page', page)
					const canvas = document.getElementById(`pdf-canvas-${num}`)
					const ctx = canvas.getContext("2d")
					const viewport = page.getViewport({ scale: state.scale })
					// 画布大小,默认值是width:300px,height:150px
					canvas.width = viewport.width
					canvas.height = viewport.height
					// 画布的dom大小, 设置移动端,宽度设置铺满整个屏幕
					const clientWidth = document.body.clientWidth - 20
					canvas.style.width = clientWidth + "px"
					// 根据pdf每页的宽高比例设置canvas的高度
					canvas.style.height =
						clientWidth * (viewport.height / viewport.width) + 'px'
					page.render({
						canvasContext: ctx,
						viewport
					})
					if (num < 5) {
						methods.renderPdf(num + 1)
					} else {
						emit("onRendered")
						proxy.$toast.clear()
					}
				})
			},
			zoomChange(value) {
				state.zoom = value == 'plus' ? state.zoom + 5 : state.zoom - 5
				let pdfViewer = document.getElementsByClassName('pdf-viewer')[0]
				let pages = document.getElementsByClassName('pdf_item')
				pdfViewer.scrollTop =
					(pages[state.currentPageNum - 1].offsetTop * state.zoom) / 10
			},
			onScroll(e) {
				let pages = document.getElementsByClassName('pdf_item')
				for (let i = 0; i < state.totalPageNum; i++) {
					let offset = e.target.offsetHeight / 2 - 100 // 距顶部的距离(当前页在滚动到页面可视区的哪个位置时更改currentPageNum)
					if (
						e.target.scrollTop >=
						(pages[i].offsetTop * state.zoom) / 10 - offset
					) {
						if (
							(pages[i + 1] &&
								e.target.scrollTop <
									(pages[i + 1].offsetTop * state.zoom) / 10 - offset) ||
							!pages[i + 1]
						) {
							state.currentPageNum = i + 1
						}
					}
				}
			}
		}
		watchEffect(() => {
			if (props.url) {
				// proxy.$toast.loading({
				// 	message: "文件加载中...",
				// 	overlay: true,
				// 	forbidClick: true,
				// 	duration: 0
				// });
				methods.resolvePdf(props.url)
			}
		})
		return {
			...toRefs(state),
			...methods
		}
	}
}
</script>
<style lang="less" scoped>
// @import "@/common/css/global.scss";
.pdf_viewer_container {
	.pdf_viewer {
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		padding: 10px 10px 50px;
		overflow: scroll;
		background-color: #f5f5f5;
	}
	// 放飞自我的工具栏
	.tool_bar {
		z-index: 2;
		position: absolute;
		bottom: 0;
		left: 0;
		right: 0;
		height: 45px;
		line-height: 45px;
		color: #fff;
		padding: 0 20px;
		background-color: rgba(85, 85, 85, 0.6);
		display: flex;
		justify-content: flex-end;
		.page_num {
			flex: 1;
			font-size: 17px;
		}
		.txt {
			font-size: 16px;
			padding-right: 5px;
			margin-left: 20px;
		}
		.box {
			position: relative;
			margin-top: 5px;
			width: 35px;
			height: 35px;
			line-height: 35px;
			text-align: center;
			background-color: #3476fe;
			border-radius: 50%;
			.van-icon {
				vertical-align: middle;
				font-weight: bold;
			}
			.mask {
				z-index: 1;
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				background-color: rgba(109, 109, 109, 0.7);
				border-radius: 50%;
			}
		}
	}
}
</style>
